package com.chenyuxin.ilp.security.auth.handler;


import cn.hutool.json.JSONUtil;
import com.chenyuxin.ilp.model.enums.exception.ExceptionEnums;
import com.chenyuxin.ilp.model.pojo.Result;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.PrintWriter;

@Component
public class LoginFailHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        Result result;
        if(exception instanceof LoginException){
            LoginException loginException = (LoginException) exception;
            result = Result.fail(loginException.getCode(),loginException.getMessage());
        }else{
            result = Result.fail(ExceptionEnums.SYSTEM_ERROR);
        }
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        String json = JSONUtil.toJsonStr(result);
        PrintWriter writer = response.getWriter();
        writer.print(json);
        writer.flush();
        writer.close();
    }
}
